// component/com-vie-house/com-vie-house.js
import p from '../../utils/platform'
import { debounce, throttle, matchPhoneNumber, matchAllPhoneNumber, parseDate, mathchSearchValue, encryptPhoneNumber } from '../../utils/utilsNew';
import locationBehavior from '../../behaviors/location';
const computedBehavior = require('miniprogram-computed')
import api from '../../common/api';
import constant from '../../common/constant';
const app = getApp()
Component({
  behaviors: [locationBehavior, computedBehavior],

  /**
   * 组件的属性列表
   */
  properties: {
    tabConentIndex: {
      type: Number,
      value: 0
    }
  },

  options: {
    styleIsolation: 'apply-shared',
    addGlobalClass: true,
  },

  computed: {
    tabListTitles(data) {
      return data.tabList.map(v => v.title)
    },
    typeName(data) {
      return data.tabList[data.defaultTabIndex].value
    }
  },

  /**
   * 组件的初始数据
   */
  data: {
    list: [],
    placeholder: "去搜索楼盘",
    searchTextValue: "",
    city: "",
    tabList: [
      { title: "二手", value: "二手房" },
      { title: "出租", value: "租房" },
      { title: "新房", value: "新房" },
    ],
    defaultTabIndex: 0,
    isMobileLogin: false,
    isFirstEnter: true,
    isGoCityPage: false,
    isGoSearchPage: false,
  },

  observers: {
    tabConentIndex() {
      if (this.data.tabConentIndex != 3) return

      app.globalData.searchType = ""
      this.setData({
        isMobileLogin: !!app.globalData.sessionUser.mobile
      })
      
      this.getCityBe(true)
        .then((city) => {
          console.log("当前城市==========", city);
          this.setData({ city })
          
          api.readVieHouse({
            logType: 1,
            cityName: city,
            delType: this.data.typeName
          })

          this.fetchHouse()
        })
        .catch(() => {
          wx.navigateTo({url: "/pages/home/switchCity/switchCity"})
        })
    }
  },

  lifetimes: {
    // 生命周期函数，可以为函数，或一个在methods段中定义的方法名
    attached: function() {},
    moved: function() {},
    detached: function() {},
  },

  pageLifetimes: {
    show: function() {
      if (this.data.tabConentIndex != 3) return
      
      // 页面被展示
      this.getCityBe(true)
        .then((city) => {
          console.log("抢房  show", city, app.globalData.vieSearchValue);
          this.setData({
            city,
            searchTextValue: app.globalData.vieSearchValue
          })

          app.globalData.vieSearchValue = ""
          this.fetchHouse()
        })
        .catch(() => {
          p.redirectTo({ url: '/pages/index/index' })
        })
    },
    hide: function() {
      // 页面被隐藏
    },
    resize: function(size) {
      // 页面尺寸变化
    }
  },

  /**
   * 组件的方法列表
   */
  methods: {
    handlePublish() {
      app.globalData.bannerComponent.gotoActivity("collaborate", 1)
    },
    handleCheckNumber() {
      app.mobileLogin(true)
        .catch(() => {
          p.reLaunch({
            url: "/pages/startPage/startPage"
          })

          app.globalData.afterMobileAuthorCallBack = () => {
            p.reLaunch({ url: "/pages/index/index?tabConentIndex=3" })
          }
        })
    },
    tabnavIndexChange(e) {
      let index = e.detail.index
      this.setData({
        defaultTabIndex: index
      })

      this.fetchHouse()
    },

    fetchHouse() {
      this.setData({
        list: []
      })

      this.selectComponent('#com-scroll-content').fetchHouse(1, this.apiFetch.bind(this))
    },

    handleData(rows) {
      const normalClass = "text-black"
      const specialClass = "text-red"
      rows.forEach((item) => {
        item.phone = matchPhoneNumber(item.content) || "xxx"
        if (!this.data.isMobileLogin) {
          item.content = matchAllPhoneNumber(item.content)
        }
        if (!this.data.isMobileLogin && item.phone != "xxx") {
          item.phone = encryptPhoneNumber(item.phone)
        }

        item.create_time = parseDate(item.create_time)

        if (this.data.searchTextValue) {
          item.contentList = mathchSearchValue(item.content, this.data.searchTextValue, normalClass, specialClass)
        } else {
          item.contentList = [{ color: normalClass, text: item.content }]
        }
      })
      this.setData({
        list: this.data.list.concat(rows),
      })
      console.log(this.data.list, 666)
      this.log(this.data.list.length)
    },

    apiFetch({ page, pageSize }) {
      return new Promise((resolve, reject) => {
        api.getWxMessagesHouses({
          page,
          pageSize,
          city: this.data.city,
          keyWords: this.data.searchTextValue,
          type: this.data.typeName
        }, (res) => {
          let data = res.data
          data.handleData = this.handleData.bind(this)
          resolve(res.data)

          if (app.globalData.searchType && this.data.searchTextValue && page == 1) {
            wx.gio('track', constant.SEARCH_SUCCESS, {      
              [constant.SEARCHFROM_VAR]: app.globalData.searchType,
              [constant.IFSEARCHRESULT_VAR]: !!data.content.rows.length,
              [constant.SEARCHWORD_VAR]: this.data.searchTextValue,
              [constant.SEARCHSOURCE_VAR]: constant.VIE_PAGE_SEARCH,
            })
          }
        })
      })
    },

    handleLocation() {
      this.data.isGoCityPage = true
      this.setData({
        searchTextValue: ""
      })
      // p.navigateTo({
      //   url: `/pages/vieHouse/selectCity/selectCity?city=${this.data.city}&api=getWxCity`
      // })
      wx.navigateTo({url: "/pages/home/switchCity/switchCity"})
    },

    hanldeClearSearchValue() {
      this.setData({
        searchTextValue: ""
      })

      this.fetchHouse()
    },

    hanldeGotoSearch() {
      this.data.isGoSearchPage = true
      p.navigateTo({ url: `/pages/vieHouse/commonSearch/commonSearch?placeholder=${this.data.placeholder}&appKey=vieSearchValue&searchTextValue=${this.data.searchTextValue}&hot=getVieHotKey` })
    },

    handleCall(e) {
      if (!this.data.isMobileLogin) return
      const phone = e.currentTarget.dataset.phone
      if (typeof Number(phone) != 'number') return

      api.readVieHouse({
        logType: 3,
        phoneNumber: String(phone),
        delType: this.data.typeName
      })

      p.showModal({
          content: `拨号${phone}`
        })
        .then((res) => {
          if (res.confirm) {
            api.readVieHouse({
              logType: 5,
              phoneNumber: String(phone),
              delType: this.data.typeName
            })

            p.makePhoneCall({
              phoneNumber: String(phone)
            })
          }
        })
    },

    log(length) {
      // 城市搜索log
      if (this.data.isGoCityPage) {
        this.data.isGoCityPage = false
        api.readVieHouse({
          logType: 4,
          cityName: this.data.city,
          resultNum: length,
          delType: this.data.typeName
        })
      }
  
      // 关键词搜索log
      if (this.data.isGoSearchPage) {
        this.data.isGoSearchPage = false
        api.readVieHouse({
          logType: 2,
          keyWords: this.data.searchTextValue,
          resultNum: length,
          cityName: this.data.city,
          delType: this.data.typeName
        })
      }
    },

    hanldeCopy(e) {
      const content = e.currentTarget.dataset.content
      wx.setClipboardData({
        data: content,
        success:(res) => {
          wx.gio('track', constant.ROOM_COPY_SUCCESS, {      
            [constant.ROOMTYPE_VAR]: [constant.ER_SHOU, constant.CHU_ZU, constant.XIN_FANG][this.data.defaultTabIndex],
          })
        }
      })
    },
  }
})